package com.qinge.blog.service.impl;

import com.qinge.blog.entity.BlogUser;
import com.qinge.blog.service.BlogLoginService;
import com.qinge.blog.utils.exception.ServiceException;
import com.qinge.blog.utils.jwt.JwtUtil;
import com.qinge.blog.utils.redis.RedisUtil;
import com.qinge.blog.utils.result.JsonResult;
import com.qinge.blog.utils.result.ResultCode;
import com.qinge.blog.utils.result.ResultTool;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author QDW
 * @date 2022/5/6 10:52
 * @description 登录实现类
 **/
@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public JsonResult login(BlogUser user) {
        // AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);


        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new ServiceException("登录失败");
        }

        // 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        BlogUser loginUser = (BlogUser) authenticate.getPrincipal();
        String userid = loginUser.getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("user",loginUser);
        // 把完整的用户信息存入redis  userid作为key
        redisUtil.setCacheObject("login:" + userid, loginUser);
        return ResultTool.success(map);
    }

    @Override
    public JsonResult logout(BlogUser user) {
        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal()=="anonymousUser"){
            return ResultTool.fail(ResultCode.USER_TOKEN_INVALID);
        }

        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        BlogUser loginUser = (BlogUser) authentication.getPrincipal();

        String userid = loginUser.getId().toString();
        // 删除redis中的值
        redisUtil.deleteObject("login:" + userid);

        return ResultTool.success();
    }
}
